import conf.settings as settings
from metric_reader import MetricReader
from lib.metric_exception import MetricCollectException
from lib.metric_type.load import LoadMetric, Level

NODE_LABEL = settings.NODE_LABEL
CPU_COUNT_METRIC = "sysom_proc_cpus"


class NodeLoadAvg(LoadMetric):
    def __init__(self, metric_reader: MetricReader, metric_settings,
                 level: Level):
        super().__init__(metric_reader, metric_settings, level)

    def _collect_process_metric(self):
        return self._default_single_gauge()

    # 对于节点的load average，需要根据CPU核数来确定影响，所以自定义calculate_score方法
    def _calculate_score(self, metric_value: float) -> float:
        def _count_node_cpus():
            query_args = {NODE_LABEL: self.name[Level.Node], "mode": "idle"}
            res = self._get_custom_metric(CPU_COUNT_METRIC, **query_args)
            if len(res.data) <= 0:
                raise MetricCollectException(
                    f"Get {CPU_COUNT_METRIC} metric failed!")

            return len(res.data)

        cpu_num = _count_node_cpus()
        res = self.score_interp(metric_value / cpu_num)
        score = round(float(res.tolist()), 2)

        return score
